﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Threading.Tasks;
using BoYuanCore.Framework;
using Microsoft.AspNetCore.Hosting;

namespace KeXinApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DownLoadController : ControllerBase
    {
        private readonly IHostingEnvironment _env;

        public DownLoadController(IHostingEnvironment env)
        {
            _env = env;
        }

        /// <summary>
        /// 下载txt文件测试
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("Download/Txt/{id}")]
        public async Task<IActionResult> DownloadTxtAsync(string id)
        {
            //参考 https://www.cnblogs.com/podolski/p/12682978.html

            //根据id获取数据，这里只是做个演示 手动创建数据
            var dataList = new List<dynamic> { new {Name="刘德华", Age=22}, new { Name = "王祖贤",Age= "19"}};
            
            //这里不需要使用using来关闭流. asp.net在传输流完成后会自动关闭流  
            MemoryStream ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(ms);
            //写入内容
            await sw.WriteLineAsync($"姓名,年龄");//标题行
            foreach (var data in dataList)
            {
                // Write the data 
                await sw.WriteLineAsync($"{data.Name},{data.Age}");
            }

            sw.Flush();
            ms.Position = 0;

            var contentType = "text/html;charset=utf-8";
            //生成txt文件
            return File(ms, contentType, $"{id}.txt");
        }


        /// <summary>
        /// 下载excel文件测试
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("Download/Excel/{id}")]
        public async Task<IActionResult> DownloadExcelAsync(string id)
        {
            //string filePath= _env.WebRootPath + "/DownLoad/1.txt";

            //参考 https://www.cnblogs.com/podolski/p/12682978.html

            //根据id获取数据，这里只是做个演示 手动创建数据
            DataTable dt = new DataTable("table_temp");

            dt.Columns.Add("id", typeof(int));
            dt.Columns.Add("name", typeof(string));
            dt.Columns.Add("age", typeof(int));

            DataRow dr = dt.NewRow();
            dr["id"] = 1;
            dr["name"] = "刘德华";
            dr["age"] = 19;
            dt.Rows.Add(dr);

            DataRow dr2 = dt.NewRow();
            dr2["id"] = 2;
            dr2["name"] = "张惠妹";
            dr2["age"] = 20;
            dt.Rows.Add(dr2);

            var excel = NPOIHelper.RenderToExcel(dt);

            var contentType = "application/excel";
            //生成txt文件
            return File(excel, contentType, $"{id}.xlsx");
        }

        /// <summary>
        /// 通过服务器绝对路径获取文件并下载
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("Download/File/{id}")]
        public async Task<IActionResult> DownloadFileAsync(string id)
        {
            string filePath= _env.WebRootPath + "/DownLoad/ceshi.txt";
            if (!System.IO.File.Exists(filePath))
            {
                throw new FileNotFoundException("指定的文件没找到");
            }

            var stream = new FileStream(filePath, FileMode.Open);
            var contentType = "multipart/form-data; boundary=something";
            return File(stream, contentType, $"{id}.txt");
        }

    }
}
